package com.copd.controller;

import com.copd.common.Result;
import com.copd.dto.LoginRequest;
import com.copd.entity.Permission;
import com.copd.entity.User;
import com.copd.mapper.UserMapper;
import com.copd.service.PermissionService;
import com.copd.service.UserService;
import com.copd.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

@Api(tags = "用户管理接口", description = "用户相关的接口")
@RestController
@RequestMapping("/api/users")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private PermissionService permissionService;

    @ApiOperation(value = "获取所有用户", notes = "获取系统中所有用户的信息")
    @GetMapping
    public ResponseEntity<Result<List<User>>> getAllUsers() {
        List<User> users = userMapper.getAllUsers();
        
        // 记录日志，帮助诊断问题
        logger.info("从数据库读取到 {} 个用户记录", users.size());
        users.forEach(user -> {
            logger.debug("用户记录: ID={}, 用户名={}, 角色={}", 
                        user.getUserId(), user.getUsername(), user.getRole());
            
            // 确保userId字段已设置
            if (user.getUserId() == null) {
                logger.warn("警告: 用户 {} 的ID字段为null", user.getUsername());
            }
        });
        
        // 确保响应中包含所有字段（避免JSON序列化省略某些字段）
        return ResponseEntity.ok(Result.success("获取用户列表成功", users));
    }

    @ApiOperation(value = "用户注册", notes = "注册新用户")
    @PostMapping("/register")
    public ResponseEntity<Result<String>> register(
            @ApiParam(value = "用户注册信息", required = true)
            @RequestBody User user) {
        try {
            userService.register(user);
            return ResponseEntity.ok(Result.success("注册成功"));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Result.error("400", e.getMessage()));
        }
    }

    @ApiOperation(value = "用户登录", notes = "用户登录接口")
    @PostMapping("/login")
    public ResponseEntity<Result<Map<String, Object>>> login(
            @ApiParam(value = "用户登录信息", required = true)
            @RequestBody LoginRequest loginRequest) {
        try {
            // 记录登录请求信息
            logger.debug("Login request - Username: {}, Role: {}", loginRequest.getUsername(), loginRequest.getRole());
            logger.debug("Login request - Password hash length: {}", loginRequest.getPassword() != null ? loginRequest.getPassword().length() : 0);
            
            // 验证用户
            User user = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
            
            // 验证角色
            if (!user.getRole().equalsIgnoreCase(loginRequest.getRole())) {
                logger.debug("Role mismatch - Expected: {}, Actual: {}", loginRequest.getRole(), user.getRole());
                throw new RuntimeException("用户名或密码错误");
            }
            
            // 生成 token
            String token = jwtUtil.generateToken(user.getUsername());
            
            // 构建用户信息（不包含密码）
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", user.getUserId());
            userInfo.put("username", user.getUsername());
            userInfo.put("role", user.getRole());
            userInfo.put("contactInfo", user.getContactInfo());
            userInfo.put("createTime", user.getCreateTime());
            
            // 如果是医生角色，添加医生特有字段
            if ("doctor".equalsIgnoreCase(user.getRole())) {
                userInfo.put("title", user.getTitle());
                userInfo.put("department", user.getDepartment());
                userInfo.put("yearsOfExperience", user.getYearsOfExperience());
                userInfo.put("certification", user.getCertification());
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("token", token);
            response.put("user", userInfo);
            
            return ResponseEntity.ok(Result.success("登录成功", response));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Result.error("400", e.getMessage()));
        }
    }

    @ApiOperation(value = "获取当前用户信息", notes = "获取当前登录用户的信息")
    @GetMapping("/current")
    public ResponseEntity<Result<Map<String, Object>>> getCurrentUser(HttpServletRequest request) {
        try {
            // 从请求头中获取token
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                // 从token中获取用户名
                String username = jwtUtil.extractUsername(token);
                // 根据用户名获取用户信息
                User user = userMapper.findByUsername(username);
                if (user != null) {
                    // 构建返回的用户信息
                    Map<String, Object> userInfo = new HashMap<>();
                    userInfo.put("username", user.getUsername());
                    userInfo.put("role", user.getRole());
                    userInfo.put("contactInfo", user.getContactInfo());
                    
                    logger.info("获取当前用户信息成功: {}", username);
                    return ResponseEntity.ok(Result.success("获取用户信息成功", userInfo));
                }
            }
            logger.warn("获取当前用户信息失败: 未找到用户信息");
            return ResponseEntity.status(401).body(Result.error("401", "未登录或登录已过期"));
        } catch (Exception e) {
            logger.error("获取当前用户信息失败", e);
            return ResponseEntity.status(500).body(Result.error("500", "获取用户信息失败"));
        }
    }

    @ApiOperation(value = "用户登出", notes = "用户登出接口")
    @PostMapping("/logout")
    public ResponseEntity<Result<String>> logout(HttpServletRequest request) {
        try {
            // 从请求头中获取token
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                // 从token中获取用户名
                String username = jwtUtil.extractUsername(token);
                logger.info("用户 {} 登出成功", username);
            }
            return ResponseEntity.ok(Result.success("登出成功"));
        } catch (Exception e) {
            logger.error("登出失败", e);
            return ResponseEntity.status(500).body(Result.error("500", "登出失败"));
        }
    }

    @ApiOperation(value = "更新用户系统信息", notes = "更新用户密码和手机号，只有字段不为空的情况下才会修改")
    @PutMapping("/update-info")
    public ResponseEntity<Result<String>> updateUserInfo(
            @ApiParam(value = "用户更新信息", required = true)
            @RequestBody User userInfo,
            HttpServletRequest request) {
        try {
            // 从请求头中获取token
            String token = request.getHeader("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                return ResponseEntity.status(401).body(Result.error("401", "未授权，请先登录"));
            }
            
            // 解析token获取userId
            String actualToken = token.substring(7);
            Integer userId = jwtUtil.getUserIdFromToken(actualToken);
            if (userId == null) {
                return ResponseEntity.status(401).body(Result.error("401", "无效的token"));
            }
            
            // 设置用户ID
            userInfo.setUserId(userId);
            
            // 调用服务更新用户信息
            userService.updateUserInfo(userInfo);
            
            return ResponseEntity.ok(Result.success("更新用户信息成功"));
        } catch (RuntimeException e) {
            logger.error("更新用户信息失败: ", e);
            return ResponseEntity.badRequest().body(Result.error("400", e.getMessage()));
        }
    }

    @ApiOperation(value = "获取当前用户权限", notes = "获取当前登录用户的所有权限")
    @GetMapping("/current/permissions")
    public ResponseEntity<Result<List<Permission>>> getCurrentUserPermissions(HttpServletRequest request) {
        try {
            // 从请求头中获取token
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                // 从token中获取用户ID
                Integer userId = jwtUtil.getUserIdFromToken(token);
                if (userId != null) {
                    // 获取用户的所有权限
                    List<Permission> permissions = permissionService.getPermissionsByUserId(userId);
                    
                    logger.info("获取用户ID={}的权限列表成功, 共{}个权限", userId, permissions.size());
                    return ResponseEntity.ok(Result.success("获取权限成功", permissions));
                }
            }
            logger.warn("获取当前用户权限失败: 未找到用户信息");
            return ResponseEntity.status(401).body(Result.error("401", "未登录或登录已过期"));
        } catch (Exception e) {
            logger.error("获取当前用户权限失败", e);
            return ResponseEntity.status(500).body(Result.error("500", "获取用户权限失败"));
        }
    }
    
    @ApiOperation(value = "根据用户ID获取权限", notes = "根据指定的用户ID获取该用户的所有权限")
    @GetMapping("/{userId}/permissions")
    public ResponseEntity<Result<Map<String, Object>>> getUserPermissions(
            @ApiParam(value = "用户ID", required = true, example = "1") @PathVariable Integer userId,
            HttpServletRequest request) {
        try {
            logger.info("接收到获取用户权限请求: userId={}", userId);
            
            // 从请求头中获取token
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                // 从token中获取当前用户ID
                Integer currentUserId = jwtUtil.getUserIdFromToken(token);
                
                // 检查权限：只有当前用户可以查看自己的权限，或者管理员可以查看任何用户的权限
                if (currentUserId.equals(userId) || hasAdminRole(currentUserId)) {
                    // 获取指定用户的所有权限
                    List<Permission> permissions = permissionService.getPermissionsByUserId(userId);
                    
                    // 处理权限数据，转换为前端友好的格式
                    List<String> permissionKeys = new ArrayList<>();
                    for (Permission permission : permissions) {
                        permissionKeys.add(permission.getPermissionKey());
                    }
                    
                    // 构建返回的数据结构
                    Map<String, Object> responseData = new HashMap<>();
                    responseData.put("permissions", permissions);  // 完整的权限对象列表
                    responseData.put("permissionKeys", permissionKeys);  // 仅权限键的列表
                    
                    logger.info("获取用户ID={}的权限列表成功, 共{}个权限", userId, permissions.size());
                    return ResponseEntity.ok(Result.success("获取权限成功", responseData));
                } else {
                    logger.warn("获取权限失败: 用户{}无权查看用户{}的权限", currentUserId, userId);
                    return ResponseEntity.status(403).body(Result.error("403", "无权查看其他用户的权限"));
                }
            }
            logger.warn("获取用户权限失败: 未找到用户信息");
            return ResponseEntity.status(401).body(Result.error("401", "未登录或登录已过期"));
        } catch (Exception e) {
            logger.error("获取用户权限失败", e);
            return ResponseEntity.status(500).body(Result.error("500", "获取用户权限失败"));
        }
    }
    
    @ApiOperation(value = "更新用户权限", notes = "直接设置用户的权限列表")
    @PutMapping("/{userId}/permissions")
    public ResponseEntity<Result<String>> updateUserPermissions(
            @ApiParam(value = "用户ID", required = true, example = "1") @PathVariable Integer userId,
            @ApiParam(value = "权限ID列表", required = true) @RequestBody List<String> permissionKeys,
            HttpServletRequest request) {
        try {
            logger.info("接收到更新用户权限请求: userId={}, permissionKeys={}", userId, permissionKeys);
            
            // 从请求头中获取token
            String token = request.getHeader("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                logger.warn("权限设置失败: 缺少Authorization头部");
                return ResponseEntity.status(401).body(Result.error("401", "未授权，请先登录"));
            }
            
            // 解析token获取当前用户ID
            String actualToken = token.substring(7);
            Integer currentUserId = jwtUtil.getUserIdFromToken(actualToken);
            logger.info("当前操作用户ID: {}", currentUserId);
            
            // 检查权限：只有管理员可以设置其他用户的权限
            if (!hasAdminRole(currentUserId)) {
                logger.warn("设置权限失败: 用户{}无管理员权限", currentUserId);
                return ResponseEntity.status(403).body(Result.error("403", "无权设置用户权限"));
            }
            
            // 检查用户是否存在
            User targetUser = userMapper.selectById(userId);
            if (targetUser == null) {
                logger.warn("设置权限失败: 目标用户ID={}不存在", userId);
                return ResponseEntity.status(404).body(Result.error("404", "用户不存在"));
            }
            
            logger.info("目标用户存在: {}({})", targetUser.getUsername(), targetUser.getUserId());
            
            // 更新用户权限
            boolean result = permissionService.updateUserPermissions(userId, permissionKeys);
            
            if (result) {
                logger.info("更新用户ID={}的权限成功", userId);
                return ResponseEntity.ok(Result.success("更新用户权限成功"));
            } else {
                logger.error("更新用户权限失败");
                return ResponseEntity.status(500).body(Result.error("500", "更新用户权限失败"));
            }
        } catch (Exception e) {
            logger.error("更新用户权限失败", e);
            return ResponseEntity.status(500).body(Result.error("500", "更新用户权限失败: " + e.getMessage()));
        }
    }
    
    /**
     * 检查用户是否为管理员
     */
    private boolean hasAdminRole(Integer userId) {
        User user = userMapper.selectById(userId);
        return user != null && "admin".equalsIgnoreCase(user.getRole());
    }
}